using ERP.ERPModels.Production.ProductionManagement;
using ERP.ProductionManage;
using ERP.ProductionManage.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace ERP.Web.Controllers.ProductionManagement
{
    /// <summary>
    /// 生产工单控制器
    /// </summary>
    public class ProductionWorkOrderController : Controller
    {
        private readonly IRepository<ProductionWorkOrders, int> _productionWorkOrderRepository;
        private readonly ILogger<ProductionWorkOrderController> _logger;

        public ProductionWorkOrderController(
            IRepository<ProductionWorkOrders, int> productionWorkOrderRepository,
            ILogger<ProductionWorkOrderController> logger)
        {
            _productionWorkOrderRepository = productionWorkOrderRepository;
            _logger = logger;
        }

        /// <summary>
        /// 生产工单首页
        /// </summary>
        public IActionResult Index()
        {
            return View("~/Views/ProductionWorkOrder/Index.cshtml");
        }

        /// <summary>
        /// 获取生产工单列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetList([FromQuery] GetWorkOrderInputDto input)
        {
            try
            {
                var query = await _productionWorkOrderRepository.GetQueryableAsync();

                // 应用筛选条件
                if (!string.IsNullOrWhiteSpace(input.OrderCode))
                {
                    query = query.Where(w => w.OrderCode.Contains(input.OrderCode));
                }

                if (!string.IsNullOrWhiteSpace(input.ProductCode))
                {
                    query = query.Where(w => w.ProductCode.Contains(input.ProductCode));
                }

                if (!string.IsNullOrWhiteSpace(input.ProductName))
                {
                    query = query.Where(w => w.ProductName.Contains(input.ProductName));
                }

                if (!string.IsNullOrWhiteSpace(input.Status))
                {
                    query = query.Where(w => w.Status == input.Status);
                }

                var totalCount = await query.CountAsync();

                query = query.OrderByDescending(p => p.Id)
                            .Skip(input.SkipCount)
                            .Take(input.MaxResultCount);

                var workOrders = await query.ToListAsync();

                var workOrderDtos = workOrders.Select(w => new WorkOrderDto
                {
                    Id = w.Id,
                    OrderCode = w.OrderCode,
                    OrderName = w.OrderName,
                    SourceType = w.SourceType,
                    Status = w.Status,
                    ProductCode = w.ProductCode,
                    ProductName = w.ProductName,
                    Specification = w.Specification,
                    Unit = w.Unit,
                    Quantity = w.Quantity,
                    RequiredDate = w.RequiredDate,
                    BatchNumber = w.BatchNumber,
                    Remarks = w.Remarks
                }).ToList();

                return Json(new
                {
                    code = 0,
                    msg = "获取成功",
                    count = totalCount,
                    data = workOrderDtos
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产工单列表失败");
                return Json(new { code = 500, msg = "获取生产工单列表失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取生产工单详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetById(int id)
        {
            try
            {
                var workOrder = await _productionWorkOrderRepository.GetAsync(id);
                var workOrderDto = new WorkOrderDto
                {
                    Id = workOrder.Id,
                    OrderCode = workOrder.OrderCode,
                    OrderName = workOrder.OrderName,
                    SourceType = workOrder.SourceType,
                    Status = workOrder.Status,
                    ProductCode = workOrder.ProductCode,
                    ProductName = workOrder.ProductName,
                    Specification = workOrder.Specification,
                    Unit = workOrder.Unit,
                    Quantity = workOrder.Quantity,
                    RequiredDate = workOrder.RequiredDate,
                    BatchNumber = workOrder.BatchNumber,
                    Remarks = workOrder.Remarks
                };

                return Json(new { code = 0, msg = "获取成功", data = workOrderDto });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产工单详情失败");
                return Json(new { code = 500, msg = "获取生产工单详情失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取生产工单甘特图数据
        /// </summary>
        [HttpGet]
        [Route("api/ProductionWorkOrder/GetGanttData")]
        public async Task<IActionResult> ShowProdction(int pageIndex = 1, int pageSize = 100, string orderName = "")
        {
            try
            {
                var query = await _productionWorkOrderRepository.GetQueryableAsync();

                // 应用筛选条件
                if (!string.IsNullOrWhiteSpace(orderName))
                {
                    query = query.Where(w => w.OrderName.Contains(orderName));
                }

                var totalCount = await query.CountAsync();

                var skip = (pageIndex - 1) * pageSize;
                query = query.OrderByDescending(p => p.Id)
                            .Skip(skip)
                            .Take(pageSize);

                var workOrders = await query.ToListAsync();

                var workOrderDtos = workOrders.Select(w => new
                {
                    id = w.Id,
                    orderCode = w.OrderCode,
                    orderName = w.OrderName,
                    sourceType = w.SourceType,
                    documentStatus = w.Status,
                    productionCode = w.ProductCode,
                    productionName = w.ProductName,
                    specifications = w.Specification,
                    orderCount = w.Quantity,
                    unit = w.Unit,
                    demandDate = w.RequiredDate,
                    customerCode = "",
                    customerName = "",
                    batchNumber = w.BatchNumber,
                    remarks = w.Remarks
                }).ToList();

                return Json(new
                {
                    code = 0,
                    msg = "获取成功",
                    count = totalCount,
                    data = workOrderDtos
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产工单甘特图数据失败");
                return Json(new { code = 500, msg = "获取生产工单甘特图数据失败：" + ex.Message });
            }
        }
        
        /// <summary>
        /// 工单表单页（新增/编辑）
        /// </summary>
        public async Task<IActionResult> Form(int? id)
        {
            if (id.HasValue)
            {
                try
                {
                    var workOrder = await _productionWorkOrderRepository.GetAsync(id.Value);
                    return View("~/Views/ProductionManagement/ProductionWorkOrder/Form.cshtml", workOrder);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取生产工单信息失败");
                    return View("~/Views/ProductionManagement/ProductionWorkOrder/Form.cshtml", new ProductionWorkOrders());
                }
            }
            return View("~/Views/ProductionManagement/ProductionWorkOrder/Form.cshtml", new ProductionWorkOrders());
        }

        /// <summary>
        /// 工单详情页
        /// </summary>
        public async Task<IActionResult> Detail(int id)
        {
            try
            {
                var workOrder = await _productionWorkOrderRepository.GetAsync(id);
                return View("~/Views/ProductionManagement/ProductionWorkOrder/Detail.cshtml", workOrder);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取生产工单详情失败");
                return NotFound();
            }
        }

        /// <summary>
        /// 删除生产工单
        /// </summary>
        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _productionWorkOrderRepository.DeleteAsync(id);
                return Json(new { code = 0, msg = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除生产工单失败");
                return Json(new { code = 500, msg = "删除生产工单失败：" + ex.Message });
            }
        }
    }
} 